package com.example.loginmybatis.controller;

import com.cloume.commons.rest.response.RestResponse;
import com.cloume.commons.verify.Verifier;
import com.example.loginmybatis.annotation.Log;
import com.example.loginmybatis.model.AuthUser;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;

/**
 * @Author: jie lu
 * @Data: 2021/12/15
 * @Version: 1.0
 * @Description:
 **/
public class AuthController {

    @Autowired
    private IAuthUserService authUserService;
    /**
     * 使用用户名密码登录系统
     *
     * @param request
     * @throws IOException
     */
    @Log("登录")
    @ApiOperation(value = "登录接口")
    @PostMapping("/login")
    public RestResponse<?> loginWithUsernamePassword(HttpServletRequest request, @RequestBody Map<String, String> body) {
        if (!new Verifier()
                .rule("username")
                .rule("password")
                .verify(body)) {
            return RestResponse.bad(-1, "invalid input");
        }
        log.info("username-password login: {}", body);
        String username = body.get("username");
        String password = body.get("password");
        AuthUser authUser = authUserService.findByUsername(username);
        if (authUser == null) {
            return RestResponse.bad(-3, "该用户名不存在或已被禁用，请核实后再登录!");
        }
        try {
            SpringContextUtil.injectPrincipalToSecurityContext(authUser, password);
            if (!authUser.getActivated()) {
                authUser.setActivateTime(System.currentTimeMillis());
                authUser.setActivated(true);
                authUserService.save(authUser);
            }
            if (authUser.getUserType() != null) {
                if (authUser.getUserType().equals(Constant.AUTH_OPERATOR)) {
                    request.getSession().setAttribute(Constant.OPERATOR, authUser.getOperator());
                } else if (authUser.getUserType().equals(Constant.AUTH_BRAND)) {
                    request.getSession().setAttribute(Constant.BRAND, authUser.getBrand());
                } else if (authUser.getUserType().equals(Constant.AUTH_FUNDER)) {
                    request.getSession().setAttribute(Constant.FUNDER, authUser.getFunder());
                }
            } else {
                request.getSession().setAttribute(Constant.OPERATOR, null);
                request.getSession().setAttribute(Constant.BRAND, null);
                request.getSession().setAttribute(Constant.FUNDER, null);
            }
            log.info("username-password login success: {}", authUser.getUsername());
            return RestResponse.good("ok");
        } catch (Exception e) {
            log.error("username-password login error: {}", e.getLocalizedMessage());
            return RestResponse.bad(-2, "用户名或密码错误!");
        }
    }
}
